package com.handle.common.log.publish;

import com.handle.common.core.constants.Constant;
import com.handle.common.core.utils.ContextHolderUtils;
import com.handle.common.core.utils.CusAccessObjectUtil;
import com.handle.common.core.utils.IPAddressUtils;
import com.handle.common.log.context.SpringContextHolder;
import com.handle.common.log.event.SysLoginLogEvent;
import com.handle.system.api.entity.SysLoginLog;
import eu.bitwalker.useragentutils.UserAgent;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author zhangqing
 * @version V1.0
 * @description 事件发布工厂
 * @date 6/3/2021 12:49 PM
 */
public class PublishFactory {
    /**
     * 记录登陆信息
     *
     * @param loginName 登录名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     */
    public static void recordLoginLog(final String loginName, final String status, final String message,final String tenantCode, final Object... args) {
        HttpServletRequest request = ContextHolderUtils.getRequest();
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        final String ip = CusAccessObjectUtil.getIpAddress(request);
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SysLoginLog sysLoginLog = SysLoginLog.builder()
                .tenantCode(tenantCode)
                .loginName(loginName)
                .ipaddr(ip)
                .loginLocation(IPAddressUtils.getRealAddress(ip))
                .network(IPAddressUtils.getNetwork(ip))
                .browser(browser)
                .os(os)
                .msg(message)
                .build();

        // 日志状态
        if (Constant.LOGIN_SUCCESS.equals(status) || Constant.LOGOUT.equals(status)) {
            sysLoginLog.setStatus(Boolean.TRUE);
        } else if (Constant.LOGIN_FAIL.equals(status)) {
            sysLoginLog.setStatus(Boolean.FALSE);
        }
        // 发布事件
        SpringContextHolder.publishEvent(new SysLoginLogEvent(sysLoginLog));
    }
}
